import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:like_button/like_button.dart';
import 'dart:io';

import 'index.dart';

class VideoDetailPage extends GetView<VideoDetailController> {
  const VideoDetailPage({Key? key}) : super(key: key);

  // Main view
  Widget _buildView() {
    return Obx(() {
      if (controller.isLoading.value) {
        return Center(child: CircularProgressIndicator(color: Colors.white));
      }

      if (controller.videos.isEmpty) {
        return Center(
          child: Text(
            'No Videos',
            style: TextStyle(color: Colors.white, fontSize: 16.sp),
          ),
        );
      }

      return PageView.builder(
        controller: controller.pageController,
        scrollDirection: Axis.vertical,
        itemCount: controller.videos.length,
        onPageChanged: controller.onPageChanged,
        itemBuilder: (context, index) {
          final video = controller.videos[index];
          return _buildVideoItem(video, index);
        },
      );
    });
  }

  // Build single video item
  Widget _buildVideoItem(RecommendedVideo video, int index) {
    final isCurrent = controller.currentIndex.value == index;

    return Stack(
      children: [
        // Video player
        _buildVideoPlayer(video, isCurrent),

        // Top action area
        Positioned(
          top: 56.h,
          left: 20.w,
          right: 20.w,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                onTap: () {
                  Get.back();
                },
                child: Icon(
                  IconFontIcons.iconBack,
                  color: Colors.white,
                  size: 28.sp,
                ),
              ),
              Text(
                'Video',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
              GestureDetector(
                onTap: () => controller.reportVideo(video),
                child: Icon(
                  IconFontIcons.iconReport,
                  color: Colors.white,
                  size: 28.sp,
                ),
              ),
            ],
          ),
        ),

        // Right side actions
        Positioned(right: 16.w, bottom: 120.h, child: _buildSideActions(video)),

        // Bottom info area
        Positioned(
          left: 16.w,
          right: 60.w,
          bottom: 30.h,
          child: _buildVideoInfo(video),
        ),
      ],
    );
  }

  // Build video player
  Widget _buildVideoPlayer(RecommendedVideo video, bool isCurrent) {
    if (video.videoUrl.isEmpty) {
      // Show placeholder
      return Container(
        color: Colors.black,
        child: Center(
          child: Icon(Icons.video_library, color: Colors.white, size: 48.sp),
        ),
      );
    }

    return VideoPlayerWidget(
      videoUrl: video.videoUrl,
      isPlaying: isCurrent,
      coverUrl: video.thumbnailUrl,
    );
  }

  // Build side action buttons
  Widget _buildSideActions(RecommendedVideo video) {
    if (video.id == null) return SizedBox();

    return GetBuilder<VideoDetailController>(
      id: 'video_detail',
      builder: (_) {
        final videoId = video.id!;
        final isFavorited = controller.favoriteStatus[videoId] ?? false;
        final isLiked = controller.likeStatus[videoId] ?? false;
        final favoriteCount = controller.favoriteCounts[videoId] ?? 0;
        final likeCount = controller.likeCounts[videoId] ?? 0;

        return Column(
          children: [
            // Favorite button
            Column(
              children: [
                LikeButton(
                  size: 50.w,
                  isLiked: isFavorited,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFFFF5722),
                    end: Color(0xFFFFC107),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFFFF5722),
                    dotSecondaryColor: Color(0xFFFFC107),
                    dotThirdColor: Color(0xFFFF9800),
                    dotLastColor: Color(0xFFF44336),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconLikeFill
                          : IconFontIcons.iconLike,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 32.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    controller.toggleFavorite();
                    return isFavorited;
                  },
                ),
                SizedBox(height: 4.h),
                Text(
                  favoriteCount > 999
                      ? '${favoriteCount ~/ 1000}k'
                      : favoriteCount.toString(),
                  style: TextStyle(color: Colors.white, fontSize: 12.sp),
                ),
              ],
            ),

            SizedBox(height: 20.h),

            // Like button
            Column(
              children: [
                LikeButton(
                  size: 50.w,
                  isLiked: isLiked,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFF00DDFF),
                    end: Color(0xFF0099CC),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFF33B5E5),
                    dotSecondaryColor: Color(0xFF0099CC),
                    dotThirdColor: Color(0xFF00DDFF),
                    dotLastColor: Color(0xFF00AACC),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconGoodFill
                          : IconFontIcons.iconGood,
                      color: isLiked ? Colors.yellow : Colors.white,
                      size: 32.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    controller.toggleLike();
                    return isLiked;
                  },
                ),
                SizedBox(height: 4.h),
                Text(
                  likeCount > 999
                      ? '${likeCount ~/ 1000}k'
                      : likeCount.toString(),
                  style: TextStyle(color: Colors.white, fontSize: 12.sp),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  // Build video info - only show video description
  Widget _buildVideoInfo(RecommendedVideo video) {
    final description = video.description;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Video description
        Container(
          padding: EdgeInsets.symmetric(vertical: 26.h, horizontal: 12.w),
          decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Text(
            description,
            style: TextStyle(
              color: Colors.white,
              fontSize: 15.sp,
              fontWeight: FontWeight.w500,
              fontFamily: 'Inter',
            ),
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.black,
        width: double.infinity,
        height: double.infinity,
        child: GetBuilder<VideoDetailController>(
          id: 'video_detail',
          builder: (_) => _buildView(),
        ),
      ),
    );
  }
}

// Video player component
class VideoPlayerWidget extends StatefulWidget {
  final String videoUrl;
  final bool isPlaying;
  final String? coverUrl;

  const VideoPlayerWidget({
    Key? key,
    required this.videoUrl,
    required this.isPlaying,
    this.coverUrl,
  }) : super(key: key);

  @override
  State<VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<VideoPlayerWidget> {
  VideoPlayerController? _controller;
  bool _isInitialized = false;
  bool _isError = false;
  bool _showPlayButton = true;
  String? _errorMessage;
  bool _isRetrying = false;
  int _retryCount = 0;
  static const int _maxRetries = 2;

  @override
  void initState() {
    super.initState();
    _initializeVideoPlayer();
  }

  @override
  void didUpdateWidget(VideoPlayerWidget oldWidget) {
    super.didUpdateWidget(oldWidget);

    // Reinitialize when URL changes or playing state changes
    if (oldWidget.videoUrl != widget.videoUrl) {
      _disposeVideoPlayer();
      _initializeVideoPlayer();
    } else if (oldWidget.isPlaying != widget.isPlaying &&
        _controller != null &&
        _isInitialized) {
      _updatePlayingState();
    }
  }

  void _initializeVideoPlayer() {
    // Reset state
    _isInitialized = false;
    _isError = false;
    _errorMessage = null;

    try {
      // Check if URL is valid
      if (widget.videoUrl.isEmpty) {
        setState(() {
          _isError = true;
          _errorMessage = 'Video URL is empty';
        });
        EasyLoading.showError('Video URL is empty');
        return;
      }

      print('Initializing video player, URL: ${widget.videoUrl}');

      // Process video path
      String videoPath = widget.videoUrl;

      // If not starting with assets/, try to build assets path
      if (!videoPath.startsWith('assets/')) {
        // Extract filename
        String fileName = videoPath;
        if (videoPath.contains('/')) {
          fileName = videoPath.split('/').last;
        }

        // Build assets path
        videoPath = 'assets/videos/$fileName';
        if (!fileName.contains('.')) {
          videoPath += '.mp4';
        }
      }

      print('Using asset path: $videoPath');
      _controller = VideoPlayerController.asset(videoPath);

      _controller!
          .initialize()
          .then((_) {
            if (mounted) {
              setState(() {
                _isInitialized = true;
                _showPlayButton = !widget.isPlaying;
                _retryCount = 0;
                _isRetrying = false;

                // Loop playback
                _controller!.setLooping(true);

                // Start playing if needed
                if (widget.isPlaying) {
                  _controller!.play();
                }
              });
            }
          })
          .catchError((error) {
            print('Video player initialization failed: $error');

            if (mounted) {
              // Try to retry
              if (_retryCount < _maxRetries && !_isRetrying) {
                _retryInitialization();
              } else {
                setState(() {
                  _isError = true;
                  _errorMessage =
                      'Cannot play video, please check if file exists';
                  _isRetrying = false;
                });
                EasyLoading.showError('Failed to load video');
              }
            }
          });

      // Listen to playback status
      _controller!.addListener(_controllerListener);
    } catch (e) {
      print('Error creating video player: $e');
      setState(() {
        _isError = true;
        _errorMessage = 'Video loading failed';
      });
      EasyLoading.showError('Video loading error');
    }
  }

  // Retry initialization
  void _retryInitialization() {
    if (_isRetrying) return;

    setState(() {
      _isRetrying = true;
    });

    _retryCount++;
    print(
      'Retrying video player initialization (${_retryCount}/${_maxRetries})',
    );

    // Dispose old controller
    _disposeVideoPlayer();

    // Retry after a delay
    Future.delayed(Duration(seconds: 1), () {
      if (mounted) {
        _initializeVideoPlayer();
      }
    });
  }

  // Controller listener
  void _controllerListener() {
    if (!mounted || _controller == null) return;

    final isPlaying = _controller!.value.isPlaying;
    if (_showPlayButton == isPlaying) {
      setState(() {
        _showPlayButton = !isPlaying;
      });
    }
  }

  void _updatePlayingState() {
    if (_controller == null || !_isInitialized) return;

    if (widget.isPlaying) {
      _controller!.play();
    } else {
      _controller!.pause();
    }
  }

  void _togglePlay() {
    if (_controller == null || !_isInitialized) return;

    setState(() {
      if (_controller!.value.isPlaying) {
        _controller!.pause();
      } else {
        _controller!.play();
      }
    });
  }

  void _disposeVideoPlayer() {
    if (_controller != null) {
      _controller!.removeListener(_controllerListener);
      _controller!.dispose();
      _controller = null;
    }
  }

  // Try to reload video
  void _reloadVideo() {
    setState(() {
      _isError = false;
      _errorMessage = null;
      _retryCount = 0;
    });
    _disposeVideoPlayer();
    _initializeVideoPlayer();
  }

  @override
  void dispose() {
    _disposeVideoPlayer();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Error state
    if (_isError) {
      return _buildErrorDisplay();
    }

    // Initialized state
    if (_isInitialized && _controller != null) {
      return GestureDetector(
        onTap: _togglePlay,
        child: Stack(
          alignment: Alignment.center,
          children: [
            // Video player
            SizedBox.expand(
              child: FittedBox(
                fit: BoxFit.cover,
                child: SizedBox(
                  width: _controller!.value.size.width,
                  height: _controller!.value.size.height,
                  child: VideoPlayer(_controller!),
                ),
              ),
            ),
            // Play button
            if (_showPlayButton)
              Container(
                padding: EdgeInsets.all(16.r),
                decoration: BoxDecoration(
                  color: Colors.black45,
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.play_arrow, color: Colors.white, size: 50.r),
              ),
          ],
        ),
      );
    }

    // Loading or showing cover image
    return _buildLoadingDisplay();
  }

  // Loading display
  Widget _buildLoadingDisplay() {
    // 如果有封面图，显示封面图
    if (widget.coverUrl != null && widget.coverUrl!.isNotEmpty) {
      return Stack(
        fit: StackFit.expand,
        children: [
          // 封面图
          _buildCoverImage(),

          // 加载指示器
          Center(
            child: Container(
              padding: EdgeInsets.all(16.r),
              decoration: BoxDecoration(
                color: Colors.black45,
                shape: BoxShape.circle,
              ),
              child: CircularProgressIndicator(color: Colors.white),
            ),
          ),
        ],
      );
    }

    // 没有封面图时显示默认加载界面
    return Stack(
      fit: StackFit.expand,
      children: [
        // Background
        Container(
          color: Colors.black,
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.video_library, color: Colors.white54, size: 60.r),
                SizedBox(height: 10.h),
                Text(
                  'Preparing video...',
                  style: TextStyle(color: Colors.white70, fontSize: 16.sp),
                ),
              ],
            ),
          ),
        ),

        // Loading indicator
        Center(child: CircularProgressIndicator(color: Colors.white)),
      ],
    );
  }

  // 构建封面图
  Widget _buildCoverImage() {
    final coverUrl = widget.coverUrl;
    if (coverUrl == null || coverUrl.isEmpty) {
      return Container(color: Colors.black);
    }

    // 处理不同类型的图片路径
    if (coverUrl.startsWith('/')) {
      try {
        final file = File(coverUrl);
        if (file.existsSync()) {
          return Image.file(
            file,
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          );
        }
      } catch (e) {
        debugPrint('加载文件图片失败: $e');
      }
      return Container(color: Colors.black);
    }

    // 处理资源路径
    return Image.asset(
      coverUrl,
      fit: BoxFit.cover,
      width: double.infinity,
      height: double.infinity,
    );
  }

  // Error display
  Widget _buildErrorDisplay() {
    return Container(
      color: Colors.black,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error_outline, color: Colors.red, size: 60.r),
            SizedBox(height: 16.h),
            Text(
              _errorMessage ?? 'Video loading failed',
              style: TextStyle(color: Colors.white, fontSize: 16.sp),
            ),
            SizedBox(height: 20.h),
            ElevatedButton(
              onPressed: _reloadVideo,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
              ),
              child: Text('Retry', style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      ),
    );
  }
}
